﻿Imports HMSDataLayer
Imports HMSLibrary
Imports System.Collections.ObjectModel

Public Class BillingWindow
    Implements IHMSData

    Private Sub CloseButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles CloseButton.Click
        Me.Close()
    End Sub

    Private Sub MinimizeButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MinimizeButton.Click
        Me.WindowState = Windows.WindowState.Minimized
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles CancelButton.Click
        RemarksStackPanel.Visibility = Visibility.Visible
        TaxDiscountDataGrid.Visibility = Visibility.Collapsed
        TaxDiscountStackPanel.Visibility = Visibility.Collapsed
        PaymentDetailsGrid.Visibility = Visibility.Collapsed
    End Sub

    Private Sub OtherChargesTextBlock_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles OtherChargesTextBlock.MouseLeftButtonDown
        RemarksStackPanel.Visibility = Visibility.Collapsed
        PaymentDetailsGrid.Visibility = Visibility.Collapsed
        TaxDiscountDataGrid.Visibility = Visibility.Visible
        TaxDiscountStackPanel.Visibility = Visibility.Visible
    End Sub

    Private Sub SalesBillWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        PatientControl.LoadData()
        NewBill()
    End Sub

    Private Sub NewBill()
        ActionMode = FormAction.ADD
        BillDatePicker.SelectedDate = Date.Now
        BillDatePicker.DisplayDateEnd = Date.Now
        'Dim dataProvider As New PatientDataLayer()

        Dim lstCl As List(Of Lookups)
        'lstCl = dataProvider.GetPatientNameIDList()
        'PatientNameComboBox.ItemsSource = lstCl

        Dim dataProvider1 As New MasterDataLayer()
        lstCl = dataProvider1.GetLookupList(LookupTypes.BillCategory)
        CategoryNameComboBox.ItemsSource = lstCl

        lstCl = dataProvider1.GetLookupList(LookupTypes.PaymentMode)
        PaymentModeComboBox.ItemsSource = lstCl

        Dim lk As New Lookups
        lk.ID = 0
        lk.Name = "None"
        lstCl = dataProvider1.GetBillTemplate()
        lstCl.Insert(0, lk)
        BillTemplateComboBox.ItemsSource = lstCl

        Dim lstBk As List(Of Banks)
        lstBk = dataProvider1.GetBanksList()
        BankComboBox.ItemsSource = lstBk

        billObject = New Billing
        Me.DataContext = billObject

        BillItemsDataGrid.ItemsSource = billObject.billItems
        TaxDiscountDataGrid.ItemsSource = billObject.billDisTax
    End Sub

    Dim billObject As Billing

    Private Sub SalesBillWindow_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Me.MouseDown
        DragMove()
    End Sub

    Private Sub TransSidePanel_AddButtonClickEvent() Handles TransSidePanel.AddButtonClickEvent
        AddNew()
    End Sub

    Private Sub TransSidePanel_BackButtonClickEvent() Handles TransSidePanel.BackButtonClickEvent
        ApplyPermission()
        TransSidePanel.BackVisibility = Visibility.Collapsed
        BackView()
    End Sub

    Private Sub TransSidePanel_CancelButtonClickEvent() Handles TransSidePanel.CancelButtonClickEvent
        Me.Close()
    End Sub

    Private Sub TransSidePanel_FindButtonClickEvent() Handles TransSidePanel.FindButtonClickEvent
        TransSidePanel.PrintVisibility = Visibility.Collapsed
        TransSidePanel.AddVisibility = Visibility.Collapsed
        TransSidePanel.SaveVisibility = Visibility.Collapsed
        TransSidePanel.FindVisibility = Visibility.Collapsed
        TransSidePanel.BackVisibility = Visibility.Visible
        FindData()
    End Sub

    Private Sub TransSidePanel_PrintButtonClickEvent() Handles TransSidePanel.PrintButtonClickEvent
        Dim PrintForm As New ReportViewerWindow
        PrintForm.ID = billObject.BillID
        PrintForm.ReportType = ReportsList.BillCumReceipt
        PrintForm.ShowDialog()
    End Sub

    Private Sub TransSidePanel_SaveButtonClickEvent() Handles TransSidePanel.SaveButtonClickEvent
        If SaveData() = True Then
            TransSidePanel.PrintVisibility = Visibility.Visible
            If MsgBox("Do you want to print the bill?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, CommonMessages.MessageTitle) = MsgBoxResult.Yes Then
                TransSidePanel_PrintButtonClickEvent()
            End If
        End If
    End Sub

    Private Sub ItemNameTextBox_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
        If e.Key = Key.F1 Then
            Dim lup As New LookupsWindow(LookupsList.ItemsServicesList)
            lup.Owner = Me
            lup.ShowDialog()
            Dim ItemObject As ItemsService
            ItemObject = lup.SelectedObject
            If lup.SelectedObject Is Nothing Then Exit Sub
            Dim billItemObject As BillItems
            billItemObject = DirectCast(sender, System.Windows.Controls.TextBox).DataContext
            If ItemObject.Name Is Nothing Then Exit Sub
            billItemObject.ItemName = ItemObject.Name
            billItemObject.ItemID = ItemObject.ID
            billItemObject.Rate = ItemObject.Rate
            billItemObject.UOMID = ItemObject.UOM
            billItemObject.UOMName = ItemObject.UOMName
        Else
            sender.text = ""
        End If
    End Sub

    Private Sub UOMNameTextBox_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
        If e.Key = Key.F1 Then
            Dim lup As New LookupsWindow(LookupsList.UOMList)
            lup.Owner = Me
            lup.ShowDialog()
            If lup.SelectedObject Is Nothing Then Exit Sub
            Dim ItemObject As Lookups
            ItemObject = lup.SelectedObject
            sender.text = ItemObject.Name
            sender.tag = ItemObject.ID
        End If
    End Sub

    Private Sub BillItemsDataGrid_CellEditEnding(ByVal sender As Object, ByVal e As Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs) Handles BillItemsDataGrid.CellEditEnding
        CalItemsAmt(e.Row.DataContext)
    End Sub

    Private Sub ItemsSubTotal()
        Dim subTotal As Double = 0
        For Each sbItem In billObject.billItems
            subTotal = subTotal + sbItem.Amount
        Next
        SubTotalTextBox.Text = subTotal
        ItemsOtherTotal()
    End Sub

    Private Sub ItemsOtherTotal()
        Dim subTotal As Double = 0
        For Each sbItem In billObject.billDisTax
            sbItem.Amount = (Val(SubTotalTextBox.Text) * sbItem.Rate) / 100
            subTotal = subTotal + sbItem.Amount
        Next
        OtherChargesTextBox.Text = subTotal
        CalculateNetAmt()
    End Sub

    Private Sub CalculateNetAmt()
        NetAmountTextBox.Text = Val(SubTotalTextBox.Text) + Val(OtherChargesTextBox.Text)
        ReceivedAmountTextBox.Text = Val(NetAmountTextBox.Text) - Val(AdvReceivedTextBox.Text)
    End Sub

    Private Sub TaxDiscountTextBox_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs)
        If e.Key = Key.F1 Then
            Dim lup As New LookupsWindow(LookupsList.BillCharges)
            lup.Owner = Me
            lup.ShowDialog()
            If lup.SelectedObject Is Nothing Then Exit Sub
            Dim ItemObject As Lookups
            ItemObject = lup.SelectedObject
            Dim billDisTaxtObject As BillDiscountTax
            billDisTaxtObject = DirectCast(sender, System.Windows.Controls.TextBox).DataContext
            If ItemObject.Name Is Nothing Then Exit Sub
            billDisTaxtObject.TaxDiscName = ItemObject.Name
            billDisTaxtObject.TaxDiscID = ItemObject.ID
            billDisTaxtObject.Rate = ItemObject.Rate
            billDisTaxtObject.Amount = (Val(SubTotalTextBox.Text) * ItemObject.Rate) / 100
            ItemsOtherTotal()
        End If
    End Sub

    Public Property ActionMode As HMSLibrary.FormAction Implements HMSLibrary.IHMSData.ActionMode

    Public Function DataValidation() As Boolean Implements HMSLibrary.IHMSData.DataValidation
        Try
            If String.IsNullOrEmpty(PatientControl.SelectedItem.Value) Then
                CommonMessages.ShowValidationMsg("Please select patient!")
                Return False
            End If
            If BillDatePicker.SelectedDate Is Nothing Then
                CommonMessages.ShowValidationMsg("Please select date!")
                Return False
            End If
            If Val(ReceivedAmountTextBox.Text.Trim) = 0 Then
                CommonMessages.ShowValidationMsg("Please enter payment details!")
                Return False
            End If
            If String.IsNullOrEmpty(PaymentModeComboBox.Text.Trim) Then
                CommonMessages.ShowValidationMsg("Please select payment mode!")
                ReceivedamountTextBlock_MouseLeftButtonDown(Nothing, Nothing)
                Return False
            End If
            If DischargeBillCheckBox.IsChecked = True Then
                If DischargeDatePicker.SelectedDate Is Nothing Then
                    CommonMessages.ShowValidationMsg("Please select discharge date!")
                    Return False
                End If
            End If
        Catch ex As Exception
            AppCommon.LogError(ex)
        End Try
        Return True
    End Function

    Public Sub LoadData(ByVal ID As Integer) Implements HMSLibrary.IHMSData.LoadData
        ActionMode = FormAction.EDIT
        Dim dataProvider As New BillingDataLayer()
        billObject = dataProvider.GetPatientBillByID(ID)
        If billObject Is Nothing Then Exit Sub
        BillNoTextBox.Text = ID
        BillDatePicker.SelectedDate = billObject.BillDate
        PatientControl.LoadData(billObject.PatientID)
        RemarksTextBox.Text = billObject.Remarks
        SubTotalTextBox.Text = billObject.SubTotal
        OtherChargesTextBox.Text = billObject.OtherCharges
        NetAmountTextBox.Text = billObject.NetAmt
        AdvReceivedTextBox.Text = billObject.AdvReceived
        CategoryNameComboBox.SelectedValue = billObject.BillCategory
        BillItemsDataGrid.ItemsSource = billObject.billItems
        TaxDiscountDataGrid.ItemsSource = billObject.billDisTax
        ReceivedAmountTextBox.Text = billObject.BillPaymentDetails.Amount
        If billObject.BillPaymentDetails.BankID IsNot Nothing Then BankComboBox.SelectedValue = billObject.BillPaymentDetails.BankID
        ChequeCCNoTextBox.Text = billObject.BillPaymentDetails.Cheque_CC_No
        ChqDatePicker.SelectedDate = billObject.BillPaymentDetails.ChequeDate
        PaymentModeComboBox.SelectedValue = billObject.BillPaymentDetails.PayMode
        TransSidePanel.PrintVisibility = Visibility.Visible
    End Sub

    Public Function SaveData() As Boolean Implements HMSLibrary.IHMSData.SaveData
        If DataValidation() = False Then Return False
        billObject.BillDate = BillDatePicker.SelectedDate
        billObject.PatientID = PatientControl.SelectedItem.Id
        billObject.PatientName = PatientControl.SelectedItem.Value
        billObject.Remarks = RemarksTextBox.Text
        billObject.SubTotal = Val(SubTotalTextBox.Text)
        billObject.OtherCharges = Val(OtherChargesTextBox.Text)
        billObject.NetAmt = Val(NetAmountTextBox.Text)
        billObject.AdvReceived = Val(AdvReceivedTextBox.Text)
        billObject.CreatedBy = AppCommon.loginInfo.UserID
        billObject.BillCategory = CategoryNameComboBox.SelectedValue
        If DischargeBillCheckBox.IsChecked = True Then
            billObject.IsDischargedBill = True
            billObject.DischargeDate = DischargeDatePicker.SelectedDate
        Else
            billObject.IsDischargedBill = False
            billObject.DischargeDate = Nothing
        End If
        Dim BillPaymentDetail As New BillPayDetails
        BillPaymentDetail.Amount = Val(ReceivedAmountTextBox.Text)
        If BankComboBox.SelectedValue IsNot Nothing Then BillPaymentDetail.BankID = BankComboBox.SelectedValue
        BillPaymentDetail.Cheque_CC_No = ChequeCCNoTextBox.Text.Trim
        BillPaymentDetail.ChequeDate = ChqDatePicker.SelectedDate
        BillPaymentDetail.PayMode = PaymentModeComboBox.SelectedValue
        billObject.BillPaymentDetails = BillPaymentDetail
        Dim dataProvider As New BillingDataLayer()
        If dataProvider.PatientBill(billObject, ActionMode) = 0 Then Return False
        BillNoTextBox.Text = billObject.BillID
        ActionMode = FormAction.None
        Return True
    End Function

    Public Sub AddNew() Implements HMSLibrary.IHMSData.AddNew
        BillNoTextBox.Text = String.Empty
        PaymentModeComboBox.SelectedIndex = -1
        BankComboBox.SelectedIndex = -1
        ChequeCCNoTextBox.Text = String.Empty
        ChqDatePicker.SelectedDate = Nothing
        CategoryNameComboBox.SelectedIndex = -1
        PatientControl.LoadData(0)
        'PatientNameComboBox.SelectedIndex = -1
        'PatientIDRun.Text = String.Empty
        SubTotalTextBox.Text = String.Empty
        OtherChargesTextBox.Text = String.Empty
        NetAmountTextBox.Text = String.Empty
        AdvReceivedTextBox.Text = String.Empty
        ReceivedAmountTextBox.Text = String.Empty
        RemarksTextBox.Text = String.Empty
        NewBill()
    End Sub

    'Private Sub PatientNameComboBox_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles PatientNameComboBox.SelectionChanged
    '    If PatientNameComboBox.SelectedItem Is Nothing Then Exit Sub
    '    PatientIDRun.Text = PatientNameComboBox.SelectedValue
    'End Sub

    Private Sub ReceivedamountTextBlock_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles ReceivedamountTextBlock.MouseLeftButtonDown
        RemarksStackPanel.Visibility = Visibility.Collapsed
        PaymentDetailsGrid.Visibility = Visibility.Visible
        TaxDiscountDataGrid.Visibility = Visibility.Collapsed
        TaxDiscountStackPanel.Visibility = Visibility.Visible
    End Sub

    Public Sub FindData() Implements IHMSData.FindData
        MainStack.Visibility = Visibility.Collapsed
        FindStackPanel.Visibility = Visibility.Visible
        Dim DataObject As BillingDataLayer
        Dim DataCollection As Object
        DataObject = New BillingDataLayer()
        DataCollection = DataObject.GetPatientBill
        SearchDataGrid.ItemsSource = DataCollection
    End Sub

    Public Sub BackView() Implements HMSLibrary.IHMSData.BackView
        MainStack.Visibility = Visibility.Visible
        FindStackPanel.Visibility = Visibility.Collapsed
    End Sub

    Private Sub DeleteButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

    End Sub

    Private Sub ApplyPermission()
        If AppCommon.loginInfo.IsSuperUser = True Then
            TransSidePanel.AddVisibility = Visibility.Visible
            TransSidePanel.FindVisibility = Visibility.Visible
            TransSidePanel.SaveVisibility = Visibility.Visible
            TransSidePanel.PrintVisibility = Visibility.Visible
            Exit Sub
        End If
        Dim mp As ModulePermissions
        mp = (From ml In AppCommon.loginInfo.ModulesList Where ml.Name = HMSFormName.Billing Select ml).FirstOrDefault
        If mp.Add = False Then TransSidePanel.AddVisibility = Visibility.Collapsed Else TransSidePanel.AddVisibility = Visibility.Visible
        If mp.Edit = False Then TransSidePanel.FindVisibility = Visibility.Collapsed Else TransSidePanel.FindVisibility = Visibility.Visible
        If mp.Print = False Then TransSidePanel.PrintVisibility = Visibility.Collapsed Else TransSidePanel.PrintVisibility = Visibility.Visible
    End Sub

    Private Sub TaxDiscountDataGrid_CellEditEnding(ByVal sender As Object, ByVal e As Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs) Handles TaxDiscountDataGrid.CellEditEnding
        Dim billTaxObject As BillDiscountTax = e.Row.DataContext
        If billTaxObject.Rate = 0 Or Val(SubTotalTextBox.Text) = 0 Then Exit Sub
        billTaxObject.Amount = (Val(SubTotalTextBox.Text) * billTaxObject.Rate) / 100
        ItemsOtherTotal()
    End Sub

    Public Property ID As Integer Implements HMSLibrary.IHMSData.ID

    Private Sub BillTemplateComboBox_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles BillTemplateComboBox.SelectionChanged
        If BillTemplateComboBox.SelectedItem Is Nothing Then Exit Sub
        Dim lk As Lookups = DirectCast(e.AddedItems, Object())(0)
        If lk Is Nothing Then Exit Sub
        If lk.ID > 0 Then
            Dim itemsList As List(Of ItemsService)
            Dim dataProvider1 As New MasterDataLayer()
            itemsList = dataProvider1.GetTemplateItemsList(lk.ID)
            billObject = New Billing
            For Each item In itemsList
                Dim billItemObject As New BillItems
                billItemObject.ItemName = item.Name
                billItemObject.ItemID = item.ID
                billItemObject.Rate = item.Rate
                billItemObject.UOMID = item.UOM
                billItemObject.UOMName = item.UOMName
                billItemObject.Amount = billItemObject.Rate * billItemObject.Qty
                billObject.billItems.Add(billItemObject)
            Next
            BillItemsDataGrid.ItemsSource = billObject.billItems
            TaxDiscountDataGrid.ItemsSource = billObject.billDisTax
        Else
        End If
        ItemsSubTotal()
    End Sub

    Private Sub SearchDataGrid_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles SearchDataGrid.MouseDoubleClick
        Dim bill As Billing = sender.SelectedItem
        If bill IsNot Nothing Then
            LoadData(bill.BillID)
            TransSidePanel_BackButtonClickEvent()
        End If
    End Sub

    Private Sub BillItemsDataGrid_RowEditEnding(ByVal sender As Object, ByVal e As Microsoft.Windows.Controls.DataGridRowEditEndingEventArgs) Handles BillItemsDataGrid.RowEditEnding
        CalItemsAmt(e.Row.DataContext)
    End Sub

    Private Sub CalItemsAmt(ByVal billItemObject As BillItems)
        If billItemObject.Rate = 0 Or billItemObject.Qty = 0 Then Exit Sub
        billItemObject.Amount = billItemObject.Rate * billItemObject.Qty
        ItemsSubTotal()
    End Sub

    Private Sub DischargeBillCheckBox_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles DischargeBillCheckBox.Click
        If DischargeBillCheckBox.IsChecked = True Then
            DischargeDatePicker.Visibility = Windows.Visibility.Visible
            Dim dataProvider As New BillingDataLayer()
            AdvReceivedTextBox.Text = dataProvider.GetPatientAdvAmt(PatientControl.SelectedItem.Id)
        Else
            AdvReceivedTextBox.Text = 0
            DischargeDatePicker.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub NetAmountTextBox_TextChanged(sender As Object, e As System.Windows.Controls.TextChangedEventArgs) Handles NetAmountTextBox.TextChanged, AdvReceivedTextBox.TextChanged
        CalculateNetAmt()
    End Sub
End Class
